package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExcutor implements Executor {

    private Connection connection = null;

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object[] param) throws Exception {
        connection = configuration.getDataSource().getConnection();
        String sql = mappedStatement.getSql();
        //对 sql 进行处理 因为此时sql中的参数尚未转义
        BoundSql boundSql = getBoundSql(sql);

        String finalSql = boundSql.getSqlText();

        PreparedStatement preparedStatement = getPreparedStatement(mappedStatement, boundSql, finalSql, param);

        ResultSet resultSet = preparedStatement.executeQuery();
        Class<?> resultType = mappedStatement.getResultType();
        ArrayList<Object> results = new ArrayList<>();
        while (resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultType.newInstance();
            int columCount = metaData.getColumnCount();
            for (int i = 1; i <= columCount; i++) {
                //属性名
                String columName = metaData.getColumnName(i);
                //属性值
                Object value = resultSet.getObject(columName);
                //创建属性描述器 为属性生成读写方法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columName, resultType);
                //获取读写方法
                Method writerMethod = propertyDescriptor.getWriteMethod();
                //向类中写入值
                writerMethod.invoke(o, value);
            }
            results.add(o);

        }
        return (List<E>) results;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object[] param) throws Exception {
        connection = configuration.getDataSource().getConnection();
        String sql = mappedStatement.getSql();
        //对 sql 进行处理 因为此时sql中的参数尚未转义
        BoundSql boundSql = getBoundSql(sql);

        String finalSql = boundSql.getSqlText();

        PreparedStatement preparedStatement = getPreparedStatement(mappedStatement, boundSql, finalSql, param);

        return preparedStatement.executeUpdate();
    }

    private PreparedStatement getPreparedStatement(MappedStatement mappedStatement, BoundSql boundSql, String finalSql, Object[] param) throws SQLException, NoSuchFieldException, IllegalAccessException {
        Class<?> paraterType = mappedStatement.getParamterType();
        PreparedStatement preparedStatement = connection.prepareStatement(finalSql);

        List<ParameterMapping> parameterMappingList = boundSql.getParamterMappingList();

        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String name = parameterMapping.getContent();

            Field declaredField = paraterType.getDeclaredField(name);
            declaredField.setAccessible(true);

            Object obj = declaredField.get(param[0]);
            if(declaredField.getGenericType() == String.class){
                preparedStatement.setString(i+1, obj.toString());
            }else {
                preparedStatement.setObject(i+1, obj);
            }

        }
        return preparedStatement;
    }

    private BoundSql getBoundSql(String sql) {

        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();

        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parse, parameterMappings);
        return boundSql;
    }

    @Override
    public void close() throws SQLException {

    }
}
